package com.keyroy.game.puzzle_rpg.models.animations;

import java.awt.Point;
import java.util.ArrayList;
import java.util.List;

import com.keyroy.game.puzzle_rpg.models.interfaces.AnimationListener;
import com.keyroy.game.puzzle_rpg.models.interfaces.Repaintable;
import com.keyroy.game.puzzle_rpg.models.puzzle.PuzzleMap;
import com.keyroy.game.puzzle_rpg.models.puzzle.PuzzleUtil;
import com.keyroy.game.puzzle_rpg.models.puzzle.Result;
import com.keyroy.game.puzzle_rpg.models.puzzle.Tile;

public class TilesAnimationUtil {
	private static Repaintable repaintable;
	private static PuzzleMap puzzleMap;

	public static void init(Repaintable repaintable, PuzzleMap puzzleMap) {
		TilesAnimationUtil.repaintable = repaintable;
		TilesAnimationUtil.puzzleMap = puzzleMap;
	}

	public static void startSelectedAimation(List<Result> results, final AnimationListener listener) {
		if (puzzleMap != null && results != null) {
			List<Animation> animations = new ArrayList<Animation>();

			for (int i = 0; i < results.size(); i++) {
				Result result = results.get(i);
				for (int j = 0; j < result.points.size(); j++) {
					Point point = result.points.get(j);
					Tile tile = PuzzleUtil.findTile(puzzleMap, point);
					if (tile != null) {
						animations.add(new SignTileAnimation(tile, puzzleMap.getPuzzleSet().signDuration));
					}
				}
			}

			start(animations, listener);
		}
	}

	public static void startMove(final AnimationListener listener) {
		if (puzzleMap != null) {
			List<Animation> animations = new ArrayList<Animation>();
			Tile[][] tiles = puzzleMap.tiles;
			for (int i = 0; i < tiles.length; i++) {
				for (int j = 0; j < tiles[i].length; j++) {
					Tile tile = tiles[i][j];
					if (tile != null) {
						if (tile.needMove()) {
							animations.add(new TileMoveAnimation(tile));
						}
					}
				}
			}
			start(animations, listener);
		}
	}

	private static final void start(List<Animation> animations, final AnimationListener listener) {
		if (animations.size() > 0) {
			AnimationExecuter.start(animations, new AnimationListener() {

				@Override
				public void onStart() {
					repaintable.repaint();
					listener.onStart();
				}

				@Override
				public void onComplete() {
					repaintable.repaint();
					listener.onComplete();
				}

				@Override
				public void onError(Exception exception) {
				}

			}, 40);
		}
	}

}
